﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RentHouse.Common;
using RentHouse.DTO;
using RentHouse.IService;
using RentHouse.Redis;
using RentHouse.Service.Entities;

namespace RentHouse.Service
{
    public class HouseService : IHouseService
    { 
        private readonly IIdNameService _idNameService;
        public HouseService(IIdNameService idNameService )
        {
            this._idNameService = idNameService;
        }

        /// <summary>
        /// 添加房源
        /// </summary>
        /// <param name="addDTO"></param>
        /// <returns></returns>
        public AjaxResult AddHouse(HouseAddDTO addDTO)
        {
            using (var db=new RentHouseContext())
            {
                var house = new BaseService<T_Houses>(db);
                var attachment = new BaseService<T_Attachments>(db);
                T_Houses t_Houses = new T_Houses
                {
                    StatusId=addDTO.StatusId,
                    DecorateStatusId=addDTO.DecorateStatusId,
                    Address=addDTO.Address,
                    Area=addDTO.Area,
                    CheckInDateTime=addDTO.CheckInDateTime,
                    CommunityId=addDTO.CommunityId,
                    CreateDateTime=DateTime.Now,
                    Description=addDTO.Description,
                    Direction=addDTO.Direction,
                    FloorIndex=addDTO.FloorIndex,
                    IsDeleted=false,
                    LookableDateTime=addDTO.LookableDateTime,
                    MonthRent=addDTO.MonthRent,
                    OwnerName=addDTO.OwnerName,
                    OwnerPhoneNum=addDTO.OwnerPhoneNum,
                    RoomTypeId=addDTO.RoomTypeId,
                    TypeId=addDTO.TypeId,
                    TotalFloorCount=addDTO.TotalFloorCount
                };
                foreach (var item in addDTO.AttachmentIds)
                {
                    T_Attachments attachments = attachment.Get(e => e.Id == item);
                    t_Houses.T_Attachments.Add(attachments);
                }
                if (house.Add(t_Houses) > 0)
                    return new AjaxResult(ResultState.Success, "添加成功");
                else
                    return new AjaxResult(ResultState.Success, "添加失败");
            }
        }

        /// <summary>
        /// 添加图片
        /// </summary>
        /// <param name="picDTO"></param>
        /// <returns></returns>

        public AjaxResult AddHousePic(HousePicDTO picDTO)
        {
            using (var db = new RentHouseContext())
            {
                var bs = new BaseService<T_HousePics>(db);
                var model = new T_HousePics
                {
                    CreateDateTime = DateTime.Now,
                    HouseId = picDTO.HouseId,
                    ThumbUrl = picDTO.ThumbUrl,
                    Url = picDTO.Url
                };
                long id = bs.Add(model);
                if (id>0)
                {
                    return new AjaxResult(ResultState.Success, "添加图片成功");
                }
                else
                {
                    return new AjaxResult(ResultState.Error, "添加图片失败");

                }

            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AjaxResult Delete(long id)
        {
            using (var db=new RentHouseContext())
            {
                BaseService<T_Houses> bs = new BaseService<T_Houses>(db);
                var data = bs.Get(e => e.Id == id);
                    data.T_Attachments.Clear();
                    if (bs.Delete(data))
                        return new AjaxResult(ResultState.Success, "删除成功");
                    else
                        return new AjaxResult(ResultState.Error, "删除失败");
            }
        }

        /// <summary>
        /// 获取房子的配套设施
        /// </summary>
        /// <returns></returns>
        public List<AttachmentDTO> GetAttachmentList()
        {
            using (var db = new RentHouseContext())
            {
                var attachment = new BaseService<T_Attachments>(db);
                var list = attachment.GetList(e => true).Select(e => new AttachmentDTO()
                {
                    IconName=e.IconName,
                    Id=e.Id,
                    Name=e.Name
                }).ToList();
                return list;
            }
        }

        /// <summary>
        /// 获取当前该房子的房源 信息
        /// </summary>
        /// <param name="editDTO"></param>
        /// <returns></returns>
        public HouseEditDTO GetHouseInfo(long id)
        {
            using (var db = new RentHouseContext())
            {
                var bs = new BaseService<T_Houses>(db);
                var attachBs = new BaseService<T_Attachments>(db);
                if (id>0)
                {
                    var house = bs.Get(e => e.Id == id);
                    var houseDto= new HouseEditDTO()
                    {
                        StatusId = house.StatusId,
                        DecorateStatusId = house.DecorateStatusId,
                        Address = house.Address,
                        Area = house.Area,
                        CheckInDateTime = house.CheckInDateTime,
                        CommunityId = house.CommunityId,
                        Description = house.Description,
                        Direction = house.Direction,
                        FloorIndex = house.FloorIndex,
                        IsDeleted = false,
                        LookableDateTime = house.LookableDateTime,
                        MonthRent = house.MonthRent,
                        OwnerName = house.OwnerName,
                        OwnerPhoneNum = house.OwnerPhoneNum,
                        RoomTypeId = house.RoomTypeId,
                        TypeId = house.TypeId,
                        TotalFloorCount = house.TotalFloorCount,
                        RegionId=house.T_Communities.RegionId
                    };
                    //获取所有信息
                    var houseList = attachBs.GetList(e => true);
                    //获取该房子的配套设施
                    var attachment = house.T_Attachments;
                    //获取房子的配套设施
                    houseDto.HouseAttachments = new List<HouseAttachment>();
                    foreach (var item in houseList)
                    {
                        HouseAttachment houseAttachment = new HouseAttachment()
                        {   
                            AttachmentId=item.Id,
                            Name=item.Name,
                            IsUsed= attachment.Any(e=>e.Id==item.Id)
                        };
                        houseDto.HouseAttachments.Add(houseAttachment);

                    }
                    return houseDto;
                }
                return null;
            }
        }

        /// <summary>
        /// 根据不同的租房类型显示对应页面
        /// </summary>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="communityName"></param>
        /// <param name="typeId"></param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public List<HouseDTO> GetList(int start, int length, string communityName, int typeId, ref int rowCount)
        {
            using (var db=new RentHouseContext())
            {
                var house = new BaseService<T_Houses>(db);
                var query = PredicateExtensions.True<T_Houses>();
                if (typeId>0)
                {
                    query = query.And(e => e.TypeId == typeId);
                }
                if (!string.IsNullOrWhiteSpace(communityName))
                {
                    query = query.And(e => e.T_Communities.Name == communityName);
                }
                var houseList = house.GetPagedList(start, length, ref rowCount, query, e => e.Id, false).Select(e => new HouseDTO()
                {   
                    DecorateStatusId=e.DecorateStatusId,
                    RoomTypeId=e.RoomTypeId,
                    Address=e.Address,
                    Area=e.Area,
                    Id=e.Id,
                    MonthRent=e.MonthRent,
                    CommunityName=e.T_Communities.Name,
                    RegionName=e.T_Communities.T_Regions.Name
                    
                    
                }).ToList();
               
                houseList.ForEach(e =>
                {
                    //通过RoomTypeId获取名称
                    e.RoomTypeName = _idNameService.GetIdsName(e.RoomTypeId);
                    e.DecorateStatusName = _idNameService.GetIdsName(e.DecorateStatusId);
                });
                return houseList;
            }
        }

        /// <summary>
        /// 移动端首页显示
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="cityId"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<HouseDTO> GetList(int pageIndex, int cityId, int pageSize)
        {
            using (var db = new RentHouseContext())
            {
                var house = new BaseService<T_Houses>(db);
                var query = PredicateExtensions.True<T_Houses>();
                if (cityId > 0)
                {
                    query = query.And(e => e.T_Communities.T_Regions.CityId == cityId);
                }
                int rowCount = 0;
                var houseList = house.GetPagedList((pageIndex-1)*pageSize, pageSize, ref rowCount, query, e => e.Id, false).Select(e => new HouseDTO()
                {
                    DecorateStatusId = e.DecorateStatusId,
                    RoomTypeId = e.RoomTypeId,
                    Address = e.Address,
                    Area = e.Area,
                    Id = e.Id,
                    MonthRent = e.MonthRent,
                    CommunityName = e.T_Communities.Name,
                    RegionName = e.T_Communities.T_Regions.Name,
                    FirstThumbUrl=e.T_HousePics.FirstOrDefault().ThumbUrl?? "/upload/2021/01/13/986DD9762F6F004AA2628613568FF3B8_thumb.gif"

                }).ToList();

                houseList.ForEach(e =>
                {
                    //通过RoomTypeId获取名称
                    e.RoomTypeName = _idNameService.GetIdsName(e.RoomTypeId);
                    e.DecorateStatusName = _idNameService.GetIdsName(e.DecorateStatusId);
                });
                return houseList;
            }

        }

        /// <summary>
        /// 查看已经上传的图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<HousePicDTO> GetPicList(int id)
        {
            using (var db=new RentHouseContext())
            {
                var model = new BaseService<T_HousePics>(db);
                var list = model.GetList(e => e.HouseId == id).Select(e => new HousePicDTO()
                {
                    HouseId = e.HouseId,
                    ThumbUrl = e.ThumbUrl,
                    Url = e.Url
                }).ToList();
                return list;
            }
        }

        /// <summary>
        /// 房源修改
        /// </summary>
        /// <param name="editDTO"></param>
        /// <returns></returns>
        public AjaxResult Update(HouseEditDTO editDTO)
        {
            using (var db=new RentHouseContext())
            {
                var houseService = new BaseService<T_Houses>(db);
                var attachmentService = new BaseService<T_Attachments>(db);
                T_Houses myHouse = houseService.Get(e => e.Id == editDTO.Id);

                myHouse.Id = editDTO.Id;
                myHouse.StatusId = editDTO.StatusId;
                myHouse.DecorateStatusId = editDTO.DecorateStatusId;
                myHouse.Address = editDTO.Address;
                myHouse.Area = editDTO.Area;
                myHouse.CheckInDateTime = editDTO.CheckInDateTime;
                myHouse.CommunityId = editDTO.CommunityId;
                myHouse.CreateDateTime = DateTime.Now;
                myHouse.Description = System.Web.HttpUtility.HtmlEncode(editDTO.Description);
                myHouse.Direction = editDTO.Direction;
                myHouse.FloorIndex = editDTO.FloorIndex;
                myHouse.IsDeleted = false;
                myHouse.LookableDateTime = editDTO.LookableDateTime;
                myHouse.MonthRent = editDTO.MonthRent;
                myHouse.OwnerName = editDTO.OwnerName;
                myHouse.OwnerPhoneNum = editDTO.OwnerPhoneNum;
                myHouse.RoomTypeId = editDTO.RoomTypeId;
                myHouse.TypeId = editDTO.TypeId;
                myHouse.TotalFloorCount = editDTO.TotalFloorCount;
                
                myHouse.T_Attachments.Clear();
                foreach (var item in editDTO.AttachmentIds)
                {  

                   T_Attachments attachment = attachmentService.Get(e => e.Id == item);
                    myHouse.T_Attachments.Add(attachment);
                }
                if (houseService.Update(myHouse))
                    return new AjaxResult(ResultState.Success, "修改成功");
                else
                    return new AjaxResult(ResultState.Error, "修改失败");


            };  
               
        }

        /// <summary>
        /// 获取房源详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public HouseDetailDTO GetHouseDetail(int id)
        {
            try
            {
                RedisHelper redis = new RedisHelper();
                var modelRedis = redis.HashGet<HouseDetailDTO>("GetHouseDetail", id.ToString());
                if (modelRedis != null)
                {
                    return modelRedis;
                }
                using (var db = new RentHouseContext())
                {
                    var bs = new BaseService<T_Houses>(db);
                    var houseInfo = bs.Get(e => e.Id == id);
                    var dto = new HouseDetailDTO
                    {
                        Address = houseInfo.Address,
                        Area = houseInfo.Area,
                        CommunityName = houseInfo.T_Communities.Name,
                        Id = houseInfo.Id,
                        MonthRent = houseInfo.MonthRent,
                        RegionName = houseInfo.T_Communities.T_Regions.Name,
                        LocationName = houseInfo.T_Communities.Location,
                        CheckInDateTime = houseInfo.CheckInDateTime,
                        CommunityBuiltYear = (int)houseInfo.T_Communities.BuiltYear,
                        Direction = houseInfo.Direction,
                        FloorIndex = houseInfo.FloorIndex,
                        LookableDateTime = houseInfo.LookableDateTime,
                        TotalFloorCount = houseInfo.TotalFloorCount,
                        CommunityTraffic = houseInfo.T_Communities.Traffic,
                        Description = houseInfo.Description
                    };

                    //通过构造函数注入，取得IIdNameService
                    dto.RoomTypeName = _idNameService.GetIdsName(houseInfo.RoomTypeId);
                    dto.TypeName = _idNameService.GetIdsName(houseInfo.TypeId);
                    dto.StatusName = _idNameService.GetIdsName(houseInfo.StatusId);
                    dto.DecorateStatusName = _idNameService.GetIdsName(houseInfo.DecorateStatusId);

                    //单独查
                    //var bsIds = new BaseService<T_IdNames>(db);
                    //var idNameList = bsIds.GetList(e => true);
                    //dto.RoomTypeName = idNameList.Where(e => e.Id == houseInfo.RoomTypeId).FirstOrDefault().Name;
                    //dto.TypeName = idNameList.Where(e => e.Id == houseInfo.TypeId).FirstOrDefault().Name;
                    //dto.StatusName = idNameList.Where(e => e.Id == houseInfo.StatusId).FirstOrDefault().Name;
                    //dto.DecorateStatusName = idNameList.Where(e => e.Id == houseInfo.DecorateStatusId).FirstOrDefault().Name;

                    //配套设施
                    dto.Attachments = new List<AttachmentDTO>();
                    foreach (var item in houseInfo.T_Attachments)
                    {
                        var attachment = new AttachmentDTO
                        {
                            IconName = item.IconName,
                            Id = item.Id,
                            Name = item.Name
                        };
                        dto.Attachments.Add(attachment);
                    }

                    //房源图片
                    dto.HousePics = new List<HousePicDTO>();
                    var bsHousePic = new BaseService<T_HousePics>(db);
                    var picList = bsHousePic.GetList(e => e.HouseId == id).ToList();
                    picList.ForEach(e =>
                    {
                        var housePic = new HousePicDTO
                        {
                            HouseId = e.HouseId,
                            Id = e.Id,
                            ThumbUrl = e.ThumbUrl,
                            Url = e.Url
                        };
                        dto.HousePics.Add(housePic);
                    });
                    //相似房源
                    //与当前房源在同一个小区的，认为是相同房源
                    dto.OtherHouses = bs.GetList(e => e.CommunityId == houseInfo.CommunityId).Take(3).Select(e => new HouseDTO()
                    {
                        Id = e.Id,
                        Area = e.Area,
                        CommunityName = e.T_Communities.Name,
                        MonthRent = e.MonthRent,
                        FirstThumbUrl = e.T_HousePics.FirstOrDefault().ThumbUrl,
                        RoomTypeId = e.RoomTypeId,
                        DecorateStatusId = e.DecorateStatusId
                    }).ToList();
                    dto.OtherHouses.ForEach(e =>
                    {
                        e.RoomTypeName = _idNameService.GetIdsName(e.RoomTypeId);
                        e.DecorateStatusName = _idNameService.GetIdsName(e.DecorateStatusId);
                    });
                    redis.HashSet<HouseDetailDTO>("GetHouseDetail", id.ToString(), dto);
                    return dto;
                }
            }
            catch (Exception)
            {
                using (var db = new RentHouseContext())
                {
                    var bs = new BaseService<T_Houses>(db);
                    var houseInfo = bs.Get(e => e.Id == id);
                    var dto = new HouseDetailDTO
                    {
                        Address = houseInfo.Address,
                        Area = houseInfo.Area,
                        CommunityName = houseInfo.T_Communities.Name,
                        Id = houseInfo.Id,
                        MonthRent = houseInfo.MonthRent,
                        RegionName = houseInfo.T_Communities.T_Regions.Name,
                        LocationName = houseInfo.T_Communities.Location,
                        CheckInDateTime = houseInfo.CheckInDateTime,
                        CommunityBuiltYear = (int)houseInfo.T_Communities.BuiltYear,
                        Direction = houseInfo.Direction,
                        FloorIndex = houseInfo.FloorIndex,
                        LookableDateTime = houseInfo.LookableDateTime,
                        TotalFloorCount = houseInfo.TotalFloorCount,
                        CommunityTraffic = houseInfo.T_Communities.Traffic,
                        Description = houseInfo.Description
                    };

                    //通过构造函数注入，取得IIdNameService
                    dto.RoomTypeName = _idNameService.GetIdsName(houseInfo.RoomTypeId);
                    dto.TypeName = _idNameService.GetIdsName(houseInfo.TypeId);
                    dto.StatusName = _idNameService.GetIdsName(houseInfo.StatusId);
                    dto.DecorateStatusName = _idNameService.GetIdsName(houseInfo.DecorateStatusId);

                    //单独查
                    //var bsIds = new BaseService<T_IdNames>(db);
                    //var idNameList = bsIds.GetList(e => true);
                    //dto.RoomTypeName = idNameList.Where(e => e.Id == houseInfo.RoomTypeId).FirstOrDefault().Name;
                    //dto.TypeName = idNameList.Where(e => e.Id == houseInfo.TypeId).FirstOrDefault().Name;
                    //dto.StatusName = idNameList.Where(e => e.Id == houseInfo.StatusId).FirstOrDefault().Name;
                    //dto.DecorateStatusName = idNameList.Where(e => e.Id == houseInfo.DecorateStatusId).FirstOrDefault().Name;

                    //配套设施
                    dto.Attachments = new List<AttachmentDTO>();
                    foreach (var item in houseInfo.T_Attachments)
                    {
                        var attachment = new AttachmentDTO
                        {
                            IconName = item.IconName,
                            Id = item.Id,
                            Name = item.Name
                        };
                        dto.Attachments.Add(attachment);
                    }

                    //房源图片
                    dto.HousePics = new List<HousePicDTO>();
                    var bsHousePic = new BaseService<T_HousePics>(db);
                    var picList = bsHousePic.GetList(e => e.HouseId == id).ToList();
                    picList.ForEach(e =>
                    {
                        var housePic = new HousePicDTO
                        {
                            HouseId = e.HouseId,
                            Id = e.Id,
                            ThumbUrl = e.ThumbUrl,
                            Url = e.Url
                        };
                        dto.HousePics.Add(housePic);
                    });
                    //相似房源
                    //与当前房源在同一个小区的，认为是相同房源
                    dto.OtherHouses = bs.GetList(e => e.CommunityId == houseInfo.CommunityId).Take(3).Select(e => new HouseDTO()
                    {
                        Id = e.Id,
                        Area = e.Area,
                        CommunityName = e.T_Communities.Name,
                        MonthRent = e.MonthRent,
                        FirstThumbUrl = e.T_HousePics.FirstOrDefault().ThumbUrl,
                        RoomTypeId = e.RoomTypeId,
                        DecorateStatusId = e.DecorateStatusId
                    }).ToList();
                    dto.OtherHouses.ForEach(e =>
                    {
                        e.RoomTypeName = _idNameService.GetIdsName(e.RoomTypeId);
                        e.DecorateStatusName = _idNameService.GetIdsName(e.DecorateStatusId);
                    });
                    return dto;
                }

            }

      
        }

        /// <summary>
        /// 房源查询
        /// </summary>
        /// <param name="houseSearch"></param>
        /// <returns></returns>
        public List<HouseDTO> GetListBySearch(HouseSearchOptions houseSearch)
        {
            using (var db=new  RentHouseContext())
            {
                var bs = new BaseService<T_Houses>(db);
                //当没有条件的时候查询所有包含关键字的房源，默认显示当前登录用户的房源
                var query =bs.GetList(e => e.T_Communities.T_Regions.CityId == houseSearch.CityId);
                //按区域检索
                if (houseSearch.RegionId>0)
                {
                    query=query.Where(e => e.T_Communities.RegionId == houseSearch.RegionId);
                }
                //按租金搜索
                if (houseSearch.StartMonthRent.HasValue)
                {
                    query=query.Where(e => e.MonthRent>=houseSearch.StartMonthRent.Value);
                }
                if (houseSearch.EndMonthRent.HasValue)
                {
                    query=query.Where(e => e.MonthRent <= houseSearch.EndMonthRent.Value);
                }
                //关键字
                if (!string.IsNullOrEmpty(houseSearch.Keywords))
                {
                    query = query.Where(e => e.Address.Contains(houseSearch.Keywords) || e.Description.Contains(houseSearch.Keywords));
                }
                //排序
                switch (houseSearch.OrderByType)
                {
                    case "MonthRenAsc":
                        query = query.OrderBy(e => e.MonthRent);     //月租金正序
                        break;
                    case "MonthRenDesc":
                        query = query.OrderByDescending(e => e.MonthRent);
                        break;
                    case "AreatAsc":
                        query = query.OrderBy(e => e.Area);                //面积
                        break;
                    case "AreatDesc":
                        query = query.OrderByDescending(e => e.Area);
                        break;
                    default:
                        query = query.OrderByDescending(e => e.Id);
                        break;

                }

                List<HouseDTO> houseList = query.Select(e => new HouseDTO
                {
                    Address = e.Address,
                    Area = e.Area,
                    CommunityName = e.T_Communities.Name,
                    DecorateStatusId = e.DecorateStatusId,
                    MonthRent = e.MonthRent,
                    Id = e.Id,
                    RoomTypeId = e.RoomTypeId,
                    RegionName = e.T_Communities.T_Regions.Name,
                    FirstThumbUrl = e.T_HousePics.FirstOrDefault().ThumbUrl == null ? "/upload/house/2021/01/13/8B12C9F668F3BC2CC544107517C34862_thumb.jpg" : e.T_HousePics.FirstOrDefault().ThumbUrl
                }).ToList();
                houseList.ForEach(e =>
                {
                    e.RoomTypeName = _idNameService.GetIdsName(e.RoomTypeId);
                    e.DecorateStatusName = _idNameService.GetIdsName(e.DecorateStatusId);
                });
                return houseList;
            }
        
        }

        /// <summary>
        /// 获取所有房源信息的集合
        /// </summary>
        /// <returns></returns>
        public List<HouseDetailDTO> GetDetailDTOList()
        {
            using (var db=new RentHouseContext())
            {
                var bs = new BaseService<T_Houses>(db);
                var houseList = bs.GetList(e => true);
                List<HouseDetailDTO> houseDetailsList = new List<HouseDetailDTO>();     
                foreach (var houseInfo in houseList)
                {
                    houseDetailsList.Add(GetHouseDetail((int)houseInfo.Id));
                }
                return houseDetailsList;
            }
        }
    }
}
